'use strict'

const path = require('path')
const Controller = require('egg').Controller
const sendToWormhole = require('stream-wormhole')
const multer = require('koa-multer')
const fs = require('fs')
const pump = require('mz-modules/pump')

const storage = multer.diskStorage({
  //文件保存路径
  destination: function(req, file, cb) {
    cb(null, 'public/uploads/')
  },
  //修改文件名称
  filename: function(req, file, cb) {
    var fileFormat = file.originalname.split('.')
    cb(null, Date.now() + '.' + fileFormat[fileFormat.length - 1])
  }
})

class MediaController extends Controller {
  async create() {
    const { ctx } = this

    // const stream = await ctx.getFileStream()

    // const name = path.basename(stream.filename)
    // // 文件处理，上传到云存储等等
    // // let result
    // // try {
    // //   result = await ctx.oss.put(name, stream)
    // // } catch (err) {
    // //   // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
    // //   await sendToWormhole(stream)
    // //   throw err
    // // }
    // console.log(stream)
    // ctx.body = {
    //   name
    //   // url: result.url,
    //   // 所有表单字段都能通过 `stream.fields` 获取到
    //   // fields: stream.fields
    // }

    // fs.writeFile('app/public/' + name, stream)

    const parts = this.ctx.multipart({ autoFields: true })
    const files = []

    let stream
    while ((stream = await parts()) != null) {
      // const filename = stream.filename.toLowerCase()
      const filename = Math.random()
        .toString(36)
        .substr(2)

      const target = path.join(this.config.baseDir, 'app/public', filename)
      const writeStream = fs.createWriteStream(target)
      await pump(stream, writeStream)
      files.push(filename)
    }

    ctx.body = {
      files
    }
  }

  async delete() {
    const { ctx } = this
  }

  async update() {
    const { ctx } = this
  }

  async list() {
    const { ctx } = this
  }
}

module.exports = MediaController
